#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<iostream>

int main(){

  //创建套接字
  //建立连接
  //接受数据
  int sockfd= socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  if(sockfd<0){
    return 0;
  }

  struct sockaddr_in addr;
  addr.sin_family=AF_INET;
  addr.sin_port=htons(2927);
  //" "表示 是因为要传入一个点分十进制的字符串作为参数
  //不要用公网ip
  addr.sin_addr.s_addr=inet_addr("0.0.0.0");


  int ret =bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
  if(ret<0){
    return 0;
  }
  while(1){
    char buf[1024]={0};

    struct sockaddr_in peer_addr;
    socklen_t peer_addrlen=sizeof(peer_addr);

    recvfrom(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&peer_addr,&peer_addrlen);
    printf("buf is :%s from %s port: %d \n",buf,inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
    memset(buf,'\0',sizeof(buf));
    printf("please to input:");
    //std::cout<<"please to input"<<std::endl;
    //sprintf(buf,"hello %s %d, i am server\n",inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
    std::cin>>buf;
    sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&peer_addr,peer_addrlen);
  }
  close(sockfd);
  // while(1){
  // sleep(1);
  //}
  return 0;

}
